import React, { useState } from "react";
import PropTypes from "prop-types";
import './index.scss'

export default function Search(props) {
    const [focus, setFocus] = useState(false)
    const [value, setValue] = useState('')

    const changeHandle = ({ target }) => {
        const v = target.value.trim()
        setValue(v)
    }

    const keyUpHandle = ({ keyCode }) => {
        if (keyCode === 13 && value.length > 0) {
            props.search(value)
            setValue('')
        }
    }

    const searchHandle = () => {
        if (value.length > 0) {
            props.search(value)
            setValue('')
        }
    }

    const remove = () => {
        setValue('')
    }

    return (
        <div style={ focus ? {...(props.style), borderColor: '#09AAFF'} : props.style }
             className={ 'search-warp ' + props.className }
        >
            <input type='text'
                   placeholder='搜索您的文件'
                   value={ value }
                   onFocus={ () => { setFocus(true) } }
                   onBlur={ () => { setFocus(false) } }
                   onChange={ changeHandle }
                   onKeyUp={ keyUpHandle }
            />
            <span style={ {display: value.length > 0 ? 'flex' : 'none'} }
                  className='remove-btn'
                  onClick={ remove }
            >
                <i className='icon-remove' />
            </span>
            <span className='search-btn'
                  onClick={ searchHandle }
            >
                <i className='icon-search'/>
            </span>
        </div>
    )
}

Search.propTypes = {
    style: PropTypes.object,
    className: PropTypes.string,
    search: PropTypes.func
}

Search.defaultProps = {
    style: {},
    className: '',
    search: value => { console.log(value) }
}